package com.atguigu.gmall.list.listener;

import com.atguigu.gmall.list.service.GoodsService;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 消费者 消费消息
 */
@Component
@Log4j2
public class SkuUpperOrDownListener {
    @Resource
    GoodsService goodsService;
    @RabbitListener(queues = "upper_queue")
    public void skuUpper(Message message , Channel channel){
        //获取消息内容
        String skuId = new String(message.getBody());
        //获取消息属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息编号
        long deliveryTag = messageProperties.getDeliveryTag();

        try {
            //上架
            goodsService.dbSkuAddIntoEs(Long.parseLong(skuId));
            //手动确认消息
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            try {
                if (messageProperties.getRedelivered()){
                    //消息第二次消费还是失败，将消息从队列中取出 存入日志
                    e.printStackTrace();
                    log.error("商品上架失败，失败的商品Id为"+skuId);
                    channel.basicReject(deliveryTag,false);
                }else {
                    //消息第一次确认,将第一次处理失败的消息放回队列
                    channel.basicReject(deliveryTag,true);
                }
            }catch (Exception e1){
                log.error("商品上架拒绝消息失败, 失败的商品id为:" + skuId + ",失败的原因为:" + e1.getMessage());
            }
        }

    }

    @RabbitListener(queues = "down_queue")
    public void downUpper(Message message , Channel channel){
        //获取消息内容
        String skuId = new String(message.getBody());
        //获取消息属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息编号
        long deliveryTag = messageProperties.getDeliveryTag();

        try {
            //下架
            goodsService.removeEs(Long.parseLong(skuId));
            //手动确认消息
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            try {
                if (messageProperties.getRedelivered()){
                    //消息第二次消费还是失败，将消息从队列中取出 存入日志
                    e.printStackTrace();
                    log.error("商品下架失败，失败的商品Id为"+skuId);
                    channel.basicReject(deliveryTag,false);
                }else {
                    //消息第一次确认,将第一次处理失败的消息放回队列
                    channel.basicReject(deliveryTag,true);
                }
            }catch (Exception e1){
                log.error("商品下架拒绝消息失败, 失败的商品id为:" + skuId + ",失败的原因为:" + e1.getMessage());
            }
        }

    }

}
